import { useState } from "react";

const initTableState = {
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list: []
}

const useWrapPageTable = () => {
  const [loading, setLoading] = useState(false);
  const [tableState, setTableState] = useState(initTableState);

  /** 
   * 获取表格数据
   * @param promise API请求Promise
   * @param parseListFun 如需对列表数据进行二次处理，可传入该方法
   */
  const fetchTableData = async (promise: Promise<any>, parseListFun?: any) => {
    setLoading(true);
    try {
      const res = await promise;  // 直接等待 Promise
      const { data } = res;
      setTableState({
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        total: data.total,
        list: parseListFun ? parseListFun(data.list) : data.list
      })
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }

  return { loading, setLoading, tableState, setTableState, fetchTableData }
}

export default useWrapPageTable;